// 登录组件
import React, { Component } from 'react';
import { useNavigate, Navigate } from 'react-router';

import { connect } from 'react-redux'
import { asynclogin } from '../../redux/actions'

import { Form, Input, Button, } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';

import './login.less'
import logo from '../../assets/login/logo.png'

// import { login } from '../../api/login'
// import memoryUtils from '../../utils/memoryUtils'
// import storageUtils from '../../utils/storageUtils'

function annoyCom (MessCom) {
  return (props) => {
    let navigate = useNavigate()
    console.log(props)
    return <MessCom {...props} navigate={navigate} />
  }
}

class Login extends Component {

  //提交表单且数据验证成功后回调事件
  /*
  async和await
  1. 作用?
   简化promise对象的使用: 不用再使用then()来指定成功/失败的回调函数
   以同步编码(没有回调函数了)方式实现异步流程
  2. 哪里写await?
    在返回promise的表达式左侧写await: 不想要promise, 想要promise异步执行的成功的value数据
  3. 哪里写async?
    await所在函数(最近的)定义的左侧写async
  */
  onFinish = async (values) => {
    console.log('Received values of form: ', values);
    this.props.asynclogin(values)
    // const response = await login(values)
    // //console.log(response.data);
    // const result = response.status
    // if (result === 0) {
    //   message.success("登录成功")
    //   const user = response.data
    //   //将用户信息保存到内存和本地local中
    //   memoryUtils.user = user
    //   storageUtils.saveUser(user)
    //   this.props.navigate('/home', { replace: true })
    // } else {
    //   message.error(response.msg)
    // }
  };

  //提交表单且数据验证失败后回调事件
  onFinishFailed = (errorInfo) => {
    console.log('验证失败', errorInfo);
  };

  //自定义密码的验证规则
  validatorPwd = (_, value) => {
    if (!value) {
      return Promise.reject(new Error('密码必须输入!'))
    } else if (value.length < 4) {
      return Promise.reject(new Error('密码至少4位!'))
    } else if (value.length > 12) {
      return Promise.reject(new Error('密码最多12位!'))
    } else if (!(/^[a-zA-Z0-9]+$/).test(value)) {
      return Promise.reject(new Error('密码必须是英文、数字或下划线组成!'))
    } else {
      return Promise.resolve()
    }
  }

  render () {

    //如果用户已经登录，自动跳转到管理界面
    //const user = memoryUtils.user
    const user = this.props.user
    if (user && user._id) {
      return <Navigate to="/home" />
    }
    return (
      <div className="login">
        <div className="login-header">
          <img src={logo} alt="logo" />
          <h1>React项目: 后台管理系统</h1>
        </div>
        <div className="login-content">
          <h2>用户登录</h2>
          <Form
            name="normal_login"
            className="login-form"
            initialValues={{
              remember: true,
            }}
            onFinish={this.onFinish}
            onFinishFailed={this.onFinishFailed}
          >
            <Form.Item
              name="username"
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
                {
                  min: 4,
                  message: '用户名至少4位!',
                },
                {
                  max: 12,
                  message: '用户名最多12位!',
                },
                {
                  pattern: /^[a-zA-Z0-9]+$/,
                  message: '用户名必须是英文、数字或下划线组成!',
                }
              ]}
              initialValue="admin"
            >
              <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="请输入用户名" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                {
                  validator: this.validatorPwd
                }
              ]}
            >
              <Input
                prefix={<LockOutlined className="site-form-item-icon" />}
                type="password"
                placeholder="请输入密码"
              />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" className="login-form-button">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }
}

export default connect(
  state => ({ user: state.user }),
  { asynclogin }
)(annoyCom(Login));